@model CaipuGuanliXitong.Models.RecipeIngredient

@{
    ViewData["Title"] = "新增带量食材";
}

<h2>新增带量食材</h2>

<h4>带量食材信息</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            
            <div class="form-group">
                <label class="control-label">菜谱搜索</label>
                <div class="input-group">
                    <input type="text" id="cookBookSearch" class="form-control" value="@ViewBag.CookBookSearch" placeholder="输入菜谱名称进行搜索" />
                    <div class="input-group-append">
                        <button type="button" class="btn btn-outline-secondary" onclick="searchCookBooks()">搜索菜谱</button>
                    </div>
                </div>
            </div>
            
            <div class="form-group">
                <label asp-for="CookBookId" class="control-label">菜谱</label>
                <select asp-for="CookBookId" class="form-control" asp-items="@(new SelectList(ViewBag.CookBooks, "Id", "Name"))">
                    <option value="">@(string.IsNullOrEmpty(ViewBag.CookBookSearch?.ToString()) ? "请选择菜谱（可先搜索）" : "请选择搜索结果中的菜谱")</option>
                </select>
                <span asp-validation-for="CookBookId" class="text-danger"></span>
                @if (!string.IsNullOrEmpty(ViewBag.CookBookSearch?.ToString()) && (ViewBag.CookBooks as List<CaipuGuanliXitong.Models.CookBook>)?.Count == 0)
                {
                    <small class="form-text text-muted">未找到匹配的菜谱，请尝试其他关键词</small>
                }
                else if (string.IsNullOrEmpty(ViewBag.CookBookSearch?.ToString()))
                {
                    <small class="form-text text-muted">请输入菜谱名称进行搜索，然后从搜索结果中选择</small>
                }
            </div>
            
            <div class="form-group">
                <label class="control-label">食材搜索</label>
                <div class="input-group">
                    <input type="text" id="ingredientSearch" class="form-control" placeholder="输入食材名称进行搜索" />
                    <div class="input-group-append">
                        <button type="button" class="btn btn-outline-secondary" onclick="searchIngredients()">搜索食材</button>
                    </div>
                </div>
            </div>
            
            <div class="form-group">
                <label asp-for="IngredientId" class="control-label">食材</label>
                <select asp-for="IngredientId" class="form-control" asp-items="@(new SelectList(ViewBag.Ingredients, "Id", "Name"))">
                    <option value="">请选择食材（可先搜索）</option>
                </select>
                <span asp-validation-for="IngredientId" class="text-danger"></span>
                <small class="form-text text-muted">请输入食材名称进行搜索，然后从搜索结果中选择</small>
            </div>
            
            <div class="form-group">
                <label asp-for="Quantity" class="control-label">单份用量</label>
                <input asp-for="Quantity" class="form-control" />
                <span asp-validation-for="Quantity" class="text-danger"></span>
            </div>
            
            <div class="form-group">
                <input type="submit" value="创建" class="btn btn-primary" />
                <a asp-action="Index" class="btn btn-secondary">返回列表</a>
            </div>
        </form>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    
    <script>
        $(document).ready(function () {
            // 当表单提交时，检查是否选择了菜谱和食材
            $('form').submit(function(e) {
                var cookBookId = $('#CookBookId').val();
                var ingredientId = $('#IngredientId').val();
                
                if (!cookBookId) {
                    e.preventDefault();
                    alert('请先搜索并选择一个菜谱');
                    return false;
                }
                
                if (!ingredientId) {
                    e.preventDefault();
                    alert('请先搜索并选择一个食材');
                    return false;
                }
            });
            
            // 当搜索框有内容时，按Enter键触发搜索
            $('#cookBookSearch').keypress(function(e) {
                if (e.which === 13) { // Enter键
                    searchCookBooks();
                }
            });
            
            $('#ingredientSearch').keypress(function(e) {
                if (e.which === 13) { // Enter键
                    searchIngredients();
                }
            });
        });
        
        function searchCookBooks() {
            var searchTerm = $('#cookBookSearch').val();
            if (searchTerm.length < 1) {
                alert('请输入至少1个字符进行搜索');
                return;
            }
            
            $.ajax({
                url: '@Url.Action("SearchCookBooks", "RecipeIngredient")',
                type: 'GET',
                data: { term: searchTerm },
                success: function(data) {
                    var cookBookSelect = $('#CookBookId');
                    cookBookSelect.empty();
                    cookBookSelect.append('<option value="">请选择搜索结果中的菜谱</option>');
                    
                    if (data.length > 0) {
                        $.each(data, function(index, item) {
                            cookBookSelect.append('<option value="' + item.id + '">' + item.text + '</option>');
                        });
                    } else {
                        cookBookSelect.append('<option value="">未找到匹配的菜谱</option>');
                    }
                },
                error: function() {
                    alert('搜索菜谱时发生错误，请重试');
                }
            });
        }
        
        function searchIngredients() {
            var searchTerm = $('#ingredientSearch').val();
            if (searchTerm.length < 1) {
                alert('请输入至少1个字符进行搜索');
                return;
            }
            
            $.ajax({
                url: '@Url.Action("SearchIngredients", "RecipeIngredient")',
                type: 'GET',
                data: { term: searchTerm },
                success: function(data) {
                    var ingredientSelect = $('#IngredientId');
                    ingredientSelect.empty();
                    ingredientSelect.append('<option value="">请选择搜索结果中的食材</option>');
                    
                    if (data.length > 0) {
                        $.each(data, function(index, item) {
                            ingredientSelect.append('<option value="' + item.id + '">' + item.text + '</option>');
                        });
                    } else {
                        ingredientSelect.append('<option value="">未找到匹配的食材</option>');
                    }
                },
                error: function() {
                    alert('搜索食材时发生错误，请重试');
                }
            });
        }
    </script>
}